﻿using OfficeOpenXml;
using System;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Text;

namespace SerialPortExample.Excel
{
    public class Excel
    {
        private static Lazy<Excel> instance = new Lazy<Excel>(() => new Excel());

        public static Excel Instance => instance.Value;

        private static string basePath = "C:\\PMOS\\Result\\TestResult";

        static Excel()
        {
            Init();
        }

        private static void Init()
        {
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var dir = Path.GetDirectoryName(basePath);
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            string path = $"{basePath}-{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}.xls";
            basePath = path;
            if (!File.Exists(basePath))
            {
                using (var package = new ExcelPackage())
                {
                    var worksheet = package.Workbook.Worksheets.Add("Result1");
                    worksheet.Cells[1, 1].Value = "时间";
                    for(int i = 0; i <= 23; i++)
                    {
                        worksheet.Cells[1, i+2].Value = $"Temp{i}";
                    }
                    package.SaveAs(new FileInfo(basePath));
                }
            }
        }

        public static void Write(Span<double> Temperatures)
        {
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (var writer = new ExcelPackage(new FileInfo(basePath)))
            {
                var worksheet = writer.Workbook.Worksheets[0];
                int lastRow = worksheet.Dimension.End.Row + 1;
                worksheet.Cells[lastRow, 1].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                for(int i = 0; i <= 23; i++)
                {
                    worksheet.Cells[lastRow, i+2].Value = Temperatures[i ]/10;
                }
                writer.Save();
            }
        }


    }
}
